package scau.hotel.hotel_web.controller;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import scau.hotel.hotel_model.redis.RedisCache;
import scau.hotel.hotel_service.service.CheckinInforService;
import scau.hotel.hotel_model.controller.RespBean;
import scau.hotel.hotel_sys.security.service.TokenService;
import scau.hotel.hotel_sys.service.IAuthenticationService;
import scau.hotel.hotel_sys.vo.LoginUserVo;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

@RestController
@RequestMapping("/auth")
@Api(value = "typeApi", tags = "登录控制器")
public class LoginController {

    @Resource
    IAuthenticationService authenticationService;

    @Resource
    RedisCache redisCache;

    @Resource
    TokenService tokenService;

    @Resource
    CheckinInforService checkinInforService;

    @PostMapping("/login")
    @ApiOperation("登录接口")
    public RespBean login(@RequestBody LoginUserVo loginUserVo){
        String token = authenticationService.login(loginUserVo.getUsername(),loginUserVo.getPassword());
        HashMap<String,Object> responseData = new HashMap<>();
        responseData.put("token",token);
        return RespBean.success("登录成功",responseData);
    }

    /**
     * 退出登录
     * @return
     */
    @GetMapping(value = "/logout")
    @ApiOperation("退出登录接口")
    public RespBean logout(HttpServletRequest request){
        // 1. 从请求头中获取token
        String token = request.getHeader("Authorization");
        //解析token获得claims
        Claims claims = tokenService.parseToken(token);
        //判断token是否过期
        if (tokenService.isTokenExpired(claims)) {
            throw new JwtException("token已过期");
        }
        //得到subject
        String userName = claims.getSubject();  // 获取token是设置的subject是用户名。注意subject可以是LoginUser的任意唯一字段
        this.redisCache.deleteObject(userName);
        this.checkinInforService.removeCache();
        return RespBean.success("退出登录成功");
    }

    /**
     * 获取用户登录信息
     * @return
     */
    @GetMapping(value = "/getInfo")
    @ApiOperation("获取用户名片接口")
    public RespBean getInfo() {
        return RespBean.success(authenticationService.getUserInfo());
    }
}
